import uuid

from langchain_core.messages import AIMessage, ToolMessage

from src.supabase_db.supabase import DBConnection
import logging

logger = logging.getLogger(__name__)


async def save_tool_calls_message(result: dict, user_id: str, project_id: str, node_name: str):
    """
    处理 agent 执行结果，将包含 tool_calls 的 AIMessage 匹配对应 ToolMessage，
    并将组合后的 chat_message 保存到 Supabase。
    """
    db_conn = DBConnection()
    client = await db_conn.client

    messages = result.get("messages", [])
    tool_message_map = {}

    # 提取所有 ToolMessage 并按 tool_call_id 映射
    for msg in messages:
        if isinstance(msg, ToolMessage):
            tool_call_id = msg.tool_call_id
            if tool_call_id and msg.status == "success":
                tool_message_map[tool_call_id] = msg.content

    # 查找所有带 tool_calls 的 AIMessage，并填充结果
    for msg in messages:
        if isinstance(msg, AIMessage):
            tool_calls = msg.tool_calls
            if not tool_calls:
                continue

            tool_calls_dict = []
            for toll_call in tool_calls:
                call_id = toll_call["id"]
                if call_id and call_id in tool_message_map:
                    toll_call_dict = {
                        "id": call_id,
                        "name": toll_call["name"],
                        "args": toll_call["args"],
                        "result": tool_message_map[call_id],
                        "type": toll_call["type"],
                    }
                    tool_calls_dict.append(toll_call_dict)

            # 构造一条 chat_messages 记录
            db_record = {
                "id": msg.id,
                "project_id": project_id,
                "agent": node_name,
                "content": '',
                "event_type": "tool_calls",
                "role": "assistant",
                "user_id": user_id,
                "tool_calls": tool_calls_dict,
                "finish_reason": "tool_calls",
            }

            response = await client.table('chat_messages').insert(db_record).execute()
            if hasattr(response, 'data') and response.data:
                logger.info(f"Successfully tool_calls_message {project_id} name to '{node_name}'")
            else:
                logger.error(f"Failed to ool_calls_message {project_id} name in database.")


async def save_simple_tool_calls_message(tool_calls, message_id: str, user_id: str, project_id: str, node_name: str):
    """
        单独一条tool_calls
    """
    db_conn = DBConnection()
    client = await db_conn.client

    db_record = {
        "id": message_id,
        "project_id": project_id,
        "agent": node_name,
        "content": '',
        "event_type": "tool_calls",
        "role": "assistant",
        "user_id": user_id,
        "tool_calls": tool_calls,
        "finish_reason": "tool_calls",
    }

    response = await client.table('chat_messages').insert(db_record).execute()
    if hasattr(response, 'data') and response.data:
        logger.info(f"Successfully simple_tool_calls_message {project_id} name to '{node_name}'")
    else:
        logger.error(f"Failed to simple_tool_calls_message {project_id} name in database.")


async def save_message_chunk(content: str, message_id: str, user_id: str, project_id: str, node_name: str):
    """
        保存content内容的chunk_message
    """
    db_conn = DBConnection()
    client = await db_conn.client

    # 构造一条 chat_messages 记录
    db_record = {
        "id": message_id,
        "project_id": project_id,
        "agent": node_name,
        "content": content,
        "event_type": "message_chunk",
        "role": "assistant",
        "user_id": user_id,
        "finish_reason": 'stop',
    }

    response = await client.table('chat_messages').insert(db_record).execute()
    if hasattr(response, 'data') and response.data:
        logger.info(f"Successfully message chunk {project_id} name to '{node_name}'")
    else:
        logger.error(f"Failed to cmessage chunk {project_id} name in database.")


async def save_user_message(content: str, user_id: str, project_id: str, node_name: str):
    """
        保存human_message
    """
    db_conn = DBConnection()
    client = await db_conn.client

    # 构造一条 chat_messages 记录
    db_record = {
        "id": str(uuid.uuid4()),
        "project_id": project_id,
        "agent": node_name,
        "content": content,
        "event_type": "human_message",
        "role": "user",
        "user_id": user_id
    }

    response = await client.table('chat_messages').insert(db_record).execute()
    if hasattr(response, 'data') and response.data:
        logger.info(f"Successfully chat message {project_id} name to '{node_name}'")
    else:
        logger.error(f"Failed to chat message {project_id} name in database.")

async def save_interrupt_message(content: str, message_id: str,user_id: str, project_id: str):
    """
        保存interrupt_message
    """
    db_conn = DBConnection()
    client = await db_conn.client

    # 构造一条 chat_messages 记录
    db_record = {
        "id": message_id,
        "project_id": project_id,
        "content": content,
        "event_type": "human_message",
        "role": "assistant",
        "user_id": user_id,
        "finish_reason": "interrupt"
    }

    response = await client.table('chat_messages').insert(db_record).execute()
    if hasattr(response, 'data') and response.data:
        logger.info(f"Successfully interrupt message {project_id}")
    else:
        logger.error(f"Failed to interrupt message {project_id} name in database.")